import datetime

from flask import Flask, request

from get_risk import get_risk, trans_gis
from user import DB

app = Flask(__name__)


@app.route('/', methods=['GET', 'POST'])
def index():
    global risk
    db = DB()  # 实例化一个对象
    if db.is_user(request.args['key']):  # 在用户表中找到了该用户
        # print(encode(request.args['key']))
        if request.method == 'POST':
            # 处理POST请求
            pass
        else:
            # 处理GET请求
            key = request.args['key']
            longitude = request.args['longitude']
            latitude = request.args['latitude']
            elevation = request.args['elevation']
            user_key = db.get_user(key)
            date = datetime.datetime.fromtimestamp(float(request.args['date']))
            # 计算risk
            # risk = 0.05
            trangis = str(trans_gis(longitude, latitude)).split(",")
            # 传入转换坐标
            risk = get_risk(trangis[0], trangis[1], user_key)
            # print(longitude, latitude, user_key,risk)
            # 插入位置记录
            data = (longitude, latitude, elevation, date, risk)  # 构建数据
            # print(key)
            db.insert_locations(user_key, data)
            # 回弹Risk
            # print(longitude, latitude, elevation)
        # risk = "0.01"
        return str(risk)
    else:
        return 'Key Flase'


if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5000, debug=True)
